// src/stores/content.ts
import { defineStore } from 'pinia';
import { Content, Tag } from '../types/models';
import api from '../services/api';

export const useContentStore = defineStore('content', {
  state: () => ({
    contents: [] as Content[],
    currentContent: null as Content | null,
    tags: [] as Tag[],
    loading: false,
    error: null as string | null,
    pagination: {
      page: 0,
      size: 20,
      totalElements: 0,
      totalPages: 0
    }
  }),

  actions: {
    async fetchContents(page: number = 0, size: number = 20, tagId?: number) {
      this.loading = true;
      try {
        const response = await api.getContents(page, size, tagId);
        // 初始化内容的加载状态
        this.contents = response.content.map(content => ({
          ...content,
          isLoading: false
        }));
        this.pagination = {
          page: response.number,
          size: response.size,
          totalElements: response.totalElements,
          totalPages: response.totalPages
        };
        this.error = null;
      } catch (error) {
        this.error = 'Failed to fetch contents';
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    async fetchContentById(id: number) {
      try {
        const response = await api.getContentById(id);
        this.currentContent = response;
      } catch (error) {
        this.error = 'Failed to fetch content';
        console.error(error);
      }
    },

    async fetchTags() {
      try {
        const response = await api.getTags();
        this.tags = response;
      } catch (error) {
        this.error = 'Failed to fetch tags';
        console.error(error);
      }
    },

    async rateContent(contentId: number, rating: number) {
      try {
        await api.rateContent(contentId, rating);
        // 更新本地状态
        const content = this.contents.find(c => c.id === contentId);
        if (content) {
          content.rating = rating;
        }
      } catch (error) {
        this.error = 'Failed to rate content';
        console.error(error);
      }
    },

    async toggleFavorite(contentId: number) {
      try {
        const content = this.contents.find(c => c.id === contentId);
        if (content) {
          if (content.isFavorite) {
            await api.removeFavorite(contentId);
            content.isFavorite = false;
          } else {
            await api.toggleFavorite(contentId);
            content.isFavorite = true;
          }
        }
      } catch (error) {
        this.error = 'Failed to toggle favorite';
        console.error(error);
      }
    }
  }
});